/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package econutri.servicos.recomendacao;

import econutri.util.Constants;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lomtools.persistence.GenericDAO;

/**
 *
 * @author leoomoreira
 */
public class InserirRecomendacaoXMLServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("application/xml;charset=ISO-8859-1");
        String pacienteCodigo = (request.getParameter("pacienteCodigo") == null || request.getParameter("pacienteCodigo").trim().length() == 0 ? "-1" : request.getParameter("pacienteCodigo"));
        String alimentoCodigo = (request.getParameter("alimentoCodigo") == null || request.getParameter("alimentoCodigo").trim().length() == 0 ? "-1" : request.getParameter("alimentoCodigo"));
        String refeicaoCodigo = (request.getParameter("refeicaoCodigo") == null || request.getParameter("refeicaoCodigo").trim().length() == 0 ? "-1" : request.getParameter("refeicaoCodigo"));
        String tipoCodigoStr = (request.getParameter("tipoCodigo") == null || request.getParameter("tipoCodigo").trim().length() == 0 ? "-1" : request.getParameter("tipoCodigo"));
        String xml = "";
        xml += "<result>";
        try {
            if (pacienteCodigo.equalsIgnoreCase("-1") || alimentoCodigo.equalsIgnoreCase("-1") || refeicaoCodigo.equalsIgnoreCase("-1") || tipoCodigoStr.equalsIgnoreCase("-1")) {
                throw new SQLException();
            }
            String sql = "";
            GenericDAO dao = new GenericDAO();

            if (refeicaoCodigo.equalsIgnoreCase("0")) {
                sql = "SELECT codigo FROM refeicao";
                List<Long> refeicaoList = new ArrayList<Long>();
                ResultSet rs = dao.executeQuery(sql);
                while (rs != null && rs.next()) {
                    refeicaoList.add(rs.getLong("codigo"));
                }
                int contInserir = 0;
                for (Long codigo : refeicaoList) {
                    boolean inserir = true;
                    if (tipoCodigoStr.equalsIgnoreCase(String.valueOf(Constants.RECOMENDACAO_INCLUSAO))) {
                        sql = "SELECT pacientecodigo, alimentocodigo, refeicaocodigo, tipocodigo FROM recomendacao WHERE pacientecodigo = "  + pacienteCodigo + " AND alimentocodigo = " + alimentoCodigo + " AND refeicaocodigo = " + codigo + " AND tipocodigo = " + Constants.RECOMENDACAO_INCLUSAO;
                        ResultSet rsT = dao.executeQuery(sql);
                        while (rsT != null && rsT.next()) {
                            inserir = false;
                        }
                    }
                    if (tipoCodigoStr.equalsIgnoreCase(String.valueOf(Constants.RECOMENDACAO_INIBICAO))) {
                        sql = "SELECT pacientecodigo, alimentocodigo, refeicaocodigo, tipocodigo FROM recomendacao WHERE pacientecodigo = "  + pacienteCodigo + " AND alimentocodigo = " + alimentoCodigo + " AND refeicaocodigo = " + codigo + " AND tipocodigo = " + Constants.RECOMENDACAO_INIBICAO;
                        ResultSet rsT = dao.executeQuery(sql);
                        while (rsT != null && rsT.next()) {
                            inserir = false;
                        }
                    }
                    if (inserir) {
                        sql = "" +
                            "INSERT INTO recomendacao " +
                            "(pacientecodigo, alimentocodigo, refeicaocodigo, tipocodigo) " +
                            "VALUES " +
                            "(" + pacienteCodigo + "," + alimentoCodigo + "," + codigo + "," + tipoCodigoStr + ")";
                        dao.insert(sql);
                        contInserir++;
                    }
                }
                if (contInserir == 0) {
                    throw new SQLException();
                }
            } else {
                if (tipoCodigoStr.equalsIgnoreCase(String.valueOf(Constants.RECOMENDACAO_INCLUSAO))) {
                    sql = "SELECT pacientecodigo, alimentocodigo, refeicaocodigo, tipocodigo FROM recomendacao WHERE pacientecodigo = "  + pacienteCodigo + " AND alimentocodigo = " + alimentoCodigo + " AND refeicaocodigo = " + refeicaoCodigo + " AND tipocodigo = " + Constants.RECOMENDACAO_INCLUSAO;
                    ResultSet rs = dao.executeQuery(sql);
                    while (rs != null && rs.next()) {
                        throw new SQLException();
                    }
                }
                if (tipoCodigoStr.equalsIgnoreCase(String.valueOf(Constants.RECOMENDACAO_INIBICAO))) {
                    sql = "SELECT pacientecodigo, alimentocodigo, refeicaocodigo, tipocodigo FROM recomendacao WHERE pacientecodigo = "  + pacienteCodigo + " AND alimentocodigo = " + alimentoCodigo + " AND refeicaocodigo = " + refeicaoCodigo + " AND tipocodigo = " + Constants.RECOMENDACAO_INIBICAO;
                    ResultSet rs = dao.executeQuery(sql);
                    while (rs != null && rs.next()) {
                        throw new SQLException();
                    }
                }
                sql = "" +
                    "INSERT INTO recomendacao " +
                    "(pacientecodigo, alimentocodigo, refeicaocodigo, tipocodigo) " +
                    "VALUES " +
                    "(" + pacienteCodigo + "," + alimentoCodigo + "," + refeicaoCodigo + "," + tipoCodigoStr + ")";
                dao.insert(sql);
            }
            dao.close();
            xml += "<acao>Sucesso</acao>";
        } catch (SQLException ex) {
            xml += "<acao>Fracasso</acao>";
            ex.printStackTrace();
        }
        try {
            if (pacienteCodigo.equalsIgnoreCase("-1") || alimentoCodigo.equalsIgnoreCase("-1") || refeicaoCodigo.equalsIgnoreCase("-1") || tipoCodigoStr.equalsIgnoreCase("-1")) {
                throw new SQLException();
            }
            String sql = "SELECT al.codigo, al.descricao, a.refeicaocodigo, r.descricao as refeicaodescricao, a.tipocodigo FROM recomendacao a, alimento al, refeicao r WHERE a.pacientecodigo = " + pacienteCodigo + " AND a.alimentocodigo = al.codigo AND a.refeicaocodigo = r.codigo ORDER BY a.tipocodigo, a.refeicaocodigo";
            GenericDAO dao = new GenericDAO();
            ResultSet rs = dao.executeQuery(sql);
            List<TempRecomendacao> resultList = new ArrayList<TempRecomendacao>();
            while (rs != null && rs.next()) {
                TempRecomendacao tempRecomendacao = new TempRecomendacao();
                tempRecomendacao.setAlimentoCodigo(rs.getInt("codigo"));
                tempRecomendacao.setAlimentoDescricao(rs.getString("descricao"));
                tempRecomendacao.setTipoCodigo(rs.getInt("tipocodigo"));
                tempRecomendacao.setRefeicaoCodigo(rs.getInt("refeicaocodigo"));
                tempRecomendacao.setRefeicaoDescricao(rs.getString("refeicaodescricao"));
                resultList.add(tempRecomendacao);
            }
            dao.close();
            List<Integer> tipoCodigoList = new ArrayList<Integer>();
            for (TempRecomendacao t : resultList) {
                if (! tipoCodigoList.contains(t.getTipoCodigo())) {
                    tipoCodigoList.add(t.getTipoCodigo());
                }
            }
            for (Integer tipoCodigo : tipoCodigoList) {
                xml += "<recomendacao>";
                xml += "<tipocodigo>" + tipoCodigo + "</tipocodigo>";
                List<String> refeicaoList = new ArrayList<String>();
                for (TempRecomendacao t : resultList) {
                    if (t.getTipoCodigo() == tipoCodigo && ! refeicaoList.contains(String.valueOf(t.getRefeicaoCodigo()))) {
                        refeicaoList.add(String.valueOf(t.getRefeicaoCodigo()));
                    }
                }
                for (String r : refeicaoList) {
                    xml += "<refeicao>";
                    xml += "<refeicaocodigo>" + r + "</refeicaocodigo>";
                    for (TempRecomendacao t : resultList) {
                        if (t.getTipoCodigo() == tipoCodigo && t.getRefeicaoCodigo() == Integer.parseInt(r)) {
                            xml += "<refeicaodescricao>" + t.getRefeicaoDescricao() + "</refeicaodescricao>";
                            break;
                        }
                    }
                    xml += "<itens>";
                    for (TempRecomendacao t : resultList) {
                        if (t.getTipoCodigo() == tipoCodigo && t.getRefeicaoCodigo() == Integer.parseInt(r)) {
                            xml += "<item>";
                                xml += "<codigo>" + t.getAlimentoCodigo() + "</codigo>";
                                xml += "<descricao>" + t.getAlimentoDescricao() + "</descricao>";
                            xml += "</item>";
                        }
                    }
                    xml += "</itens>";
                    xml += "</refeicao>";
                }
                xml += "</recomendacao>";
            }
        } catch (SQLException ex) {

        }
        xml += "</result>";
        PrintWriter out = response.getWriter();
        try {
            out.println(xml);
        } finally {
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
